import React, { useEffect, useState } from 'react';
import { Card, Form, message, Spin } from 'antd';
import { ProForm, ProFormRadio, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { updateCameraDetails, getCameraById } from '@/services/api/camera';

const handleEdit = async (camera_id: number, fields: API.CameraUpdateDetailsDto) => {
  const hide = message.loading('正在修改');
  try {
    const { status_code, message: msg } = await updateCameraDetails({ camera_id }, { ...fields });
    if (status_code === 200) {
      hide();
      message.success(msg);
      return true;
    }
    message.error(msg);
    return false;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

type EditCameraViewProps = {
  title: string;
  camera_id: number;
};

const EditCamera: React.FC<EditCameraViewProps> = (props) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);

  const { title, camera_id } = props;

  const handleRefresh = () => {
    setLoading(true);
    getCameraById({ camera_id }).then(({ status_code, data }) => {
      if (status_code === 200) {
        form.setFieldsValue(data);
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    handleRefresh();
  }, [form, camera_id]);

  return (
    <Spin spinning={loading}>
      <Card>
        <ProForm
          form={form}
          isKeyPressSubmit={false}
          title={title}
          onFinish={async (value) => {
            setLoading(true);
            const success = await handleEdit(camera_id, value as API.CameraUpdateDetailsDto);
            if (success) {
            }
            setLoading(false);
          }}
          onReset={() => {
            handleRefresh();
          }}
        >
          <ProFormText
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '标题为必填项',
              },
            ]}
          />
          <ProFormText
            label="拉流URL"
            name="pull_url"
            rules={[
              {
                required: true,
                message: '拉流URL为必填项',
              },
            ]}
          />
          <ProFormText label="推流URL" name="push_url" />
          <ProFormSelect
            label="预测模型"
            name="model"
            request={async () => [{ label: '暴力检测', value: 'violent_detection' }]}
            rules={[
              {
                required: true,
                message: '预测模型为必选项',
              },
            ]}
          />
          <ProFormRadio.Group
            name="status"
            label="状态"
            options={[
              {
                label: '启用',
                value: 1,
              },
              {
                label: '禁用',
                value: 2,
              },
            ]}
          />
        </ProForm>
      </Card>
    </Spin>
  );
};
export default EditCamera;
